package com.module.base.widget.pager;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.collection.LongSparseArray;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.module.base.utils.CollectionUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * author: yanxuwen
 * createDate: 2022/11/1 14:29
 * Description : 传递class类型的Fragment，支持自定义传参
 */
public class MyFragmentAdapter2 extends FragmentStateAdapter {
    private List<Long> fragmentIds = new ArrayList<>();//用于存储更新fragment的特定标识
    private HashSet<Long> creatIds = new HashSet<>();//得用hashset防重，用于存储adapter内的顺序
    private boolean isLoop = true;
    private List<Class<? extends Fragment>> fragmentList;
    public static final String EXTRA_DATA = "data";
    private OnArgumentsCallback argumentsCallback;
    private FragmentManager mFragmentManager;
    final LongSparseArray<Fragment> mFragments = new LongSparseArray<>();

    public interface OnArgumentsCallback {
        public void setArguments(Bundle bundle, int position);
    }

    /**
     * @param argumentsCallback 自定义传参回调
     */
    public MyFragmentAdapter2(@NonNull FragmentActivity fragmentActivity, List<Class<? extends Fragment>> fragmentList, boolean isLoop, OnArgumentsCallback argumentsCallback) {
        super(fragmentActivity);
        mFragmentManager = fragmentActivity.getSupportFragmentManager();
        update(fragmentList);
        this.isLoop = isLoop;
        this.argumentsCallback = argumentsCallback;
    }

    public MyFragmentAdapter2(@NonNull Fragment fragment, List<Class<? extends Fragment>> fragmentList, boolean isLoop, OnArgumentsCallback argumentsCallback) {
        super(fragment);
        mFragmentManager = fragment.getChildFragmentManager();
        update(fragmentList);
        this.isLoop = isLoop;
        this.argumentsCallback = argumentsCallback;
    }

    public void update(List<Class<? extends Fragment>> fragmentList) {
        if (CollectionUtil.isEmptyOrNull(fragmentList)) {
            return;
        }
        long tag = System.currentTimeMillis();//避免刷新重复，导致无法数据变更不了
        this.fragmentList = fragmentList;
        fragmentIds.clear();
        creatIds.clear();
        for (int i = 0; i < fragmentList.size(); i++) {
            fragmentIds.add(Long.parseLong(String.valueOf(tag + i)));
        }
        notifyDataSetChanged();
    }

    public void add(List<Class<? extends Fragment>> fragmentList) {
        long tag = System.currentTimeMillis();//避免刷新重复，导致无法数据变更不了
        this.fragmentList.addAll(fragmentList);
        for (int i = 0; i < fragmentList.size(); i++) {
            fragmentIds.add(Long.parseLong(String.valueOf(tag + i)));
        }
        notifyDataSetChanged();
    }


    @NonNull
    @Override
    public Fragment createFragment(int position) {
        if (getFragment(position) != null) {
            return getFragment(position);
        }
        Long ids = fragmentIds.get(position % fragmentList.size());
        creatIds.add(ids);//创建的时候将未添加的fragment添加进来，每次刷新都会调用这里，其次调用containsItem
        if (position >= 0 && !CollectionUtil.isEmptyOrNull(fragmentList)) {
            try {
                Fragment fragment = fragmentList.get(position % fragmentList.size()).newInstance();
                Bundle bundle = new Bundle();
                if (argumentsCallback != null) {
                    argumentsCallback.setArguments(bundle, position % fragmentList.size());
                }
                fragment.setArguments(bundle);
                long itemId = getItemId(position);
                mFragments.put(itemId, fragment);
                return fragment;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public Fragment getFragment(int position) {
        long itemId = getItemId(position);
        return mFragments.get(itemId);
    }

    @Override
    public int getItemCount() {
        if (CollectionUtil.isEmptyOrNull(fragmentList)) {
            return 0;
        }
        if (fragmentList.size() == 1) {
            return 1;
        }
        return isLoop ? Integer.MAX_VALUE : fragmentList.size();
    }

    /**
     * 这两个方法必须重写，作为数据改变刷新检测的工具
     *
     * @param position
     * @return
     */
    @Override
    public long getItemId(int position) {
        return fragmentIds.get(position % fragmentList.size());
    }

    @Override
    public boolean containsItem(long itemId) {
        return creatIds.contains(itemId);
    }

    public int getFirstPosition() {
        try {
            return (getItemCount() / fragmentList.size() / 2) * fragmentList.size();
        } catch (Exception e) {
            return 0;
        }
    }

    public void destroy() {
        fragmentList.clear();
        fragmentIds.clear();
        creatIds.clear();
        notifyDataSetChanged();
    }
}